#include "colormarker.h"
#include <QTime>
#include <QDateTime>
#include <QColor>
#include <QTimerEvent>

ColorMarker::ColorMarker(QObject *parent) :
    QObject(parent)
   , m_algorithm(RandomRGB)
   , m_curColor(Qt::black)
   , m_nColorTimer(0)
{
    qsrand(QDateTime::currentDateTime().toTime_t());
}

QColor ColorMarker::color() const
{
    return m_curColor;
}

void ColorMarker::setColor(const QColor &color)
{
    m_curColor = color;
    emit colorChanged(m_curColor);
}

QColor ColorMarker::timeColor() const
{
    QTime time = QTime::currentTime();
    int r = time.hour();
    int g = time.minute()*2;
    int b = time.second()*4;
    return QColor::fromRgb(r, g, b);
}

ColorMarker::GenerateAlgorithm ColorMarker::algorithm() const
{
    return m_algorithm;
}

void ColorMarker::setAlgorithm(ColorMarker::GenerateAlgorithm algorithm)
{
    m_algorithm = algorithm;
}

void ColorMarker::start()
{
    if (m_nColorTimer == 0){
        m_nColorTimer = startTimer(1000);
    }
}

void ColorMarker::stop()
{
    if (m_nColorTimer > 0){
        killTimer(m_nColorTimer);
        m_nColorTimer = 0;
    }
}

void ColorMarker::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_nColorTimer){
        switch (m_algorithm) {
        case RandomRGB:
            m_curColor.setRgb(qrand()%255, qrand()%255, qrand()%255);
            break;
        case RandomRed:
            m_curColor.setRed(qrand()%255);
            break;
        case RandomGreen:
            m_curColor.setGreen(qrand()%255);
            break;
        case RandomBlue:
            m_curColor.setBlue(qrand()%255);
            break;
        case LinearIncrease:
            int r = m_curColor.red() + 10;
            int g = m_curColor.green() + 10;
            int b = m_curColor.blue() + 10;
            m_curColor.setRgb(r%255, g%255, b%255);
        }
        emit colorChanged(m_curColor);
        emit currentTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }else{
        QObject::timerEvent(event);
    }
}


